package com.cristina.attention.handler.auth;

import com.alibaba.fastjson.JSON;
import com.cristina.attention.codec.Invocation;
import com.cristina.attention.dispatcher.MessageHandler;
import com.cristina.attention.manager.NettyChannelManager;
import com.cristina.attention.message.auth.AuthRequest;
import com.cristina.attention.message.auth.AuthResponse;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author by superman
 */
@Component
public class AuthHandler implements MessageHandler<AuthRequest> {

    @Resource
    private NettyChannelManager nettyChannelManager;

    @Override
    public void execute(Channel channel, AuthRequest message) {
        nettyChannelManager.addUser(channel, message.getUserId());

        AuthResponse response = AuthResponse.builder()
                .code(HttpResponseStatus.OK.code()).build();

        TextWebSocketFrame twf = new TextWebSocketFrame(JSON.toJSONString(new Invocation(AuthRequest.TYPE, response)));
        channel.writeAndFlush(twf);
    }

    @Override
    public String getType() {
        return AuthRequest.TYPE;
    }
}
